﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Xoohoo.ActionFilters.Authorization;
using Xoohoo.FilterProviders;
using Xoohoo.FilterProviders.FilterCriterion;
using Xoohoo.Infrastructure.InversionOfControl;
using Xoohoo.Infrastructure;
using Xoohoo.Models;
using Xoohoo.Models.InputModels;
using Xoohoo.Modules.Membership.Controllers;
using Xoohoo.Modules.Membership.ModelBinders;
using Xoohoo.Routing;

namespace Xoohoo.Modules.Membership
{
    public class MembershipModule : Module, IModuleMetaData
    {
        private readonly Site _site;

        public MembershipModule()
        {
            this._site = DependencyInjector.GetService<Site>();
        }

        #region Module Members

        public override string ModuleName
        {
            get {
                return "Membership";
            }
        }

        public override string AuthenticationModuleName
        {
            get
            {
                return "Admin";
            }
        }

        public override void RegisterRoutes()
        {
            //Route名称体现为：Admin.模块名.Controller名.Action名，如：Admin.Membership.User.UserList
            //需要体现在模块层之上的除外，如：Admin.Membership.SubMenu

            string[] controllerNamespaces = new string[] { "Xoohoo.Modules.Membership.Controllers" };
            string adminPath = _site.AdminPath;

            #region 菜单

            MapRoute("Admin.Membership.SubMenu"
                , adminPath + "/Membership/SubMenu"
                , new { controller = "Membership", action = "SubMenu" }
                , null
                , controllerNamespaces
                );

            #endregion

            #region 用户管理

            MapRoute("Admin.Membership.User.UserList"
                , adminPath + "/Membership/User/{pageSize}/{pageNumber}"
                , new { controller = "Membership", action = "UserList", pageSize = 10, pageNumber = 1 }
                , new { pageSize = new IsInt(1, Int32.MaxValue), pageNumber = new IsInt(1, Int32.MaxValue) }
                , controllerNamespaces
                );
      
            MapRoute("Admin.Membership.User.UserEdit"
                , adminPath + "/Membership/User/Edit/{userID}"
                , new { controller = "Membership", action = "UserAddOrEdit" }
                , new { userID = new IsInt(1, Int32.MaxValue) }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.UserAdd"
                , adminPath + "/Membership/User/Add"
                , new { controller = "Membership", action = "UserAddOrEdit" }
                , null
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.UserAddSave"
                , adminPath + "/Membership/User/Save"
                , new { controller = "Membership", action = "UserAddSave" }
                , null
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.UserEditSave"
                , adminPath + "/Membership/User/Save/{userID}"
                , new { controller = "Membership", action = "UserEditSave" }
                , new { userID = new IsInt(1, Int32.MaxValue) }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.UserRemove"
                , adminPath + "/Membership/User/Remove/{userID}"
                , new { controller = "Membership", action = "UserRemove" }
                , new { userID = new IsInt(1, Int32.MaxValue) }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.ChangeStatus"
                , adminPath + "/Membership/User/ChangeStatus/{userID}/{status}"
                , new { controller = "Membership", action = "UserChangeStatus" }
                , new { userID = new IsInt(1, Int32.MaxValue), status = new IsUserStatus() }
                , controllerNamespaces
                );

            #endregion

            #region 用户组管理

            MapRoute("Admin.Membership.User.UserGroupList"
                , adminPath + "/Membership/UserGroup"
                , new { controller = "Membership", action = "UserGroupList" }
                , null
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.UserGroupEdit"
                , adminPath + "/Membership/UserGroup/Edit/{userGroupID}"
                , new { controller = "Membership", action = "UserGroupEdit" }
                , new { userGroupID = new IsGuid() }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.UserGroupAdd"
                , adminPath + "/Membership/UserGroup/Add/{parentID}"
                , new { controller = "Membership", action = "UserGroupAdd", parentID = UrlParameter.Optional }
                , new { parentID = new IsNullableGuid() }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.UserGroupSave"
                , adminPath + "/Membership/UserGroup/Save/{userGroupID}"
                , new { controller = "Membership", action = "UserGroupSave", userGroupID = UrlParameter.Optional }
                , new { userGroupID = new IsNullableGuid() }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.UserGroupRemove"
                , adminPath + "/Membership/UserGroup/Remove/{userGroupID}"
                , new { controller = "Membership", action = "UserGroupRemove" }
                , new { userGroupID = new IsGuid() }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.UserGroupMove"
                , adminPath + "/Membership/UserGroup/Move/{userGroupID}/{target}"
                , new { controller = "Membership", action = "UserGroupMove" }
                , new { userGroupID = new IsGuid(), target = new IsMovingTarget() }
                , controllerNamespaces
                );

            #endregion

            #region 角色管理

            MapRoute("Admin.Membership.User.RoleList"
                , adminPath + "/Membership/Role"
                , new { controller = "Membership", action = "RoleList" }
                ,null
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.RoleEdit"
                , adminPath + "/Membership/Role/Edit/{roleID}"
                , new { controller = "Membership", action = "RoleAddOrEdit" }
                , new { roleID = new IsGuid() }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.RoleAdd"
                , adminPath + "/Membership/Role/Add"
                , new { controller = "Membership", action = "RoleAddOrEdit" }
                , null
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.RoleSave"
                , adminPath + "/Membership/Role/Save/{roleID}"
                , new { controller = "Membership", action = "RoleSave", roleID = UrlParameter.Optional }
                , new { roleID = new IsNullableGuid() }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.RoleRemove"
                , adminPath + "/Membership/Role/Remove/{roleID}"
                , new { controller = "Membership", action = "RoleRemove" }
                , new { roleID = new IsGuid() }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.RoleMove"
                , adminPath + "/Membership/Role/Move/{roleID}/{target}"
                , new { controller = "Membership", action = "RoleMove" }
                , new { roleID = new IsGuid(), target = new IsMovingTarget() }
                , controllerNamespaces
                );

            #endregion

            #region 权限管理

            MapRoute("Admin.Membership.User.PermissionList"
                , adminPath + "/Membership/Permission", new { controller = "Membership", action = "PermissionList" }
                , null
                , controllerNamespaces
                );
#if DEBUG

            MapRoute("Admin.Membership.User.PermissionEdit"
                , adminPath + "/Membership/Permission/Edit/{permissionID}"
                , new { controller = "Membership", action = "PermissionEdit" }
                , new { permissionID = new IsGuid() }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.PermissionAdd"
                , adminPath + "/Membership/Permission/Add/{parentID}"
                , new { controller = "Membership", action = "PermissionAdd", parentID = UrlParameter.Optional }
                , new { parentID = new IsNullableGuid() }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.PermissionSave"
                , adminPath + "/Membership/Permission/Save/{permissionID}"
                , new { controller = "Membership", action = "PermissionSave", permissionID = UrlParameter.Optional }
                , new { permissionID = new IsNullableGuid() }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.PermissionRemove"
                , adminPath + "/Membership/Permission/Remove/{permissionID}"
                , new { controller = "Membership", action = "PermissionRemove" }
                , new { permissionID = new IsGuid() }
                , controllerNamespaces
                );

            MapRoute("Admin.Membership.User.PermissionMove"
                , adminPath + "/Membership/Permission/Move/{permissionID}/{target}"
                , new { controller = "Membership", action = "PermissionMove" }
                , new { permissionID = new IsGuid(), target = new IsMovingTarget() }
                , controllerNamespaces
                );

#endif
            #endregion
        }

        public override void RegisterModelBinders(ModelBinderDictionary modelBinders)
        {

            modelBinders[typeof(UserStatus)] = new UserStatusModelBinder();
            modelBinders[typeof(UserInputAdd)] = new UserInputAddModelBinder();
            modelBinders[typeof(UserInputEdit)] = new UserInputEditModelBinder();
            modelBinders[typeof(UserSearchCriteria)] = new UserSearchCriteriaModelBinder();
            modelBinders[typeof(Xoohoo.Models.User)] = DependencyInjector.GetService<UserModelBinder>();

            modelBinders[typeof(UserGroupInput)] = new UserGroupInputModelBinder();
            modelBinders[typeof(RoleInput)] = new RoleInputModelBinder();
            modelBinders[typeof(PermissionInput)] = new PermissionInputModelBinder();
        }

        public override void RegisterFilters(FilterRegistryFilterProvider filterRegistry, GlobalFilterCollection globalFilters)
        {
            #region 菜单权限
            ControllerActionFilterCriteria subMenuCriteria = new ControllerActionFilterCriteria();
            subMenuCriteria.AddMethod<MembershipController>(s => s.SubMenu());
            filterRegistry.Add(new[] { subMenuCriteria }, new AdvancedAuthorizationFilter(DependencyInjector, user => user.HasPermission("用户管理")));
            #endregion

            #region 用户信息管理权限

            ControllerActionFilterCriteria userCriteria = new ControllerActionFilterCriteria();
            userCriteria.AddMethod<MembershipController>(s => s.UserList(null, null));
            userCriteria.AddMethod<MembershipController>(s => s.UserAddOrEdit(null));
            userCriteria.AddMethod<MembershipController>(s => s.UserAddSave(null, null));
            userCriteria.AddMethod<MembershipController>(s => s.UserEditSave(null, null));
            userCriteria.AddMethod<MembershipController>(s => s.UserRemove(0, null));
            userCriteria.AddMethod<MembershipController>(s => s.UserChangeStatus(0, 0, null));
            filterRegistry.Add(new[] { userCriteria }, new AdvancedAuthorizationFilter(DependencyInjector, user => user.HasPermission("用户信息管理")));

            #endregion

            #region 用户组管理权限

            ControllerActionFilterCriteria userGroupCriteria = new ControllerActionFilterCriteria();
            userGroupCriteria.AddMethod<MembershipController>(s => s.UserGroupList());
            userGroupCriteria.AddMethod<MembershipController>(s => s.UserGroupAdd(null));
            userGroupCriteria.AddMethod<MembershipController>(s => s.UserGroupEdit(Guid.Empty));
            userGroupCriteria.AddMethod<MembershipController>(s => s.UserGroupSave(null));
            userGroupCriteria.AddMethod<MembershipController>(s => s.UserGroupRemove(Guid.Empty));
            userGroupCriteria.AddMethod<MembershipController>(s => s.UserGroupMove(Guid.Empty, MovingTarget.Down));
            filterRegistry.Add(new[] { userGroupCriteria }, new AdvancedAuthorizationFilter(DependencyInjector, user => user.HasPermission("用户组管理")));

            #endregion

            #region 角色管理权限

            ControllerActionFilterCriteria roleCriteria = new ControllerActionFilterCriteria();
            roleCriteria.AddMethod<MembershipController>(s => s.RoleList());
            roleCriteria.AddMethod<MembershipController>(s => s.RoleAddOrEdit(null));
            roleCriteria.AddMethod<MembershipController>(s => s.RoleSave(null));
            roleCriteria.AddMethod<MembershipController>(s => s.RoleRemove(Guid.Empty));
            roleCriteria.AddMethod<MembershipController>(s => s.RoleMove(Guid.Empty, MovingTarget.Down));
            filterRegistry.Add(new[] { roleCriteria }, new AdvancedAuthorizationFilter(DependencyInjector, user => user.HasPermission("角色管理")));

            #endregion

            #region 权限管理权限

            ControllerActionFilterCriteria permissionCriteria = new ControllerActionFilterCriteria();
            permissionCriteria.AddMethod<MembershipController>(s => s.PermissionList());
#if DEBUG
            permissionCriteria.AddMethod<MembershipController>(s => s.PermissionAdd(null));
            permissionCriteria.AddMethod<MembershipController>(s => s.PermissionEdit(Guid.Empty));
            permissionCriteria.AddMethod<MembershipController>(s => s.PermissionSave(null));
            permissionCriteria.AddMethod<MembershipController>(s => s.PermissionRemove(Guid.Empty));
            permissionCriteria.AddMethod<MembershipController>(s => s.PermissionMove(Guid.Empty, MovingTarget.Down));
#endif
            filterRegistry.Add(new[] { permissionCriteria }, new AdvancedAuthorizationFilter(DependencyInjector, user => user.HasPermission("权限管理")));

            #endregion
        }

        #endregion

        #region IXoohooModuleMetaData Members

        public List<ModuleMenuItem> GetModuleMenus()
        {
            return new List<ModuleMenuItem>
            {
                new ModuleMenuItem
                {
                    Title = "用户管理",
                    SubMenuRouteName = "Admin.Membership.SubMenu",
                    ContentRouteName = "Admin.Membership.User.UserList",
                    Permission = "用户管理"            
                }
            };
        }
        public List<PermissionInput> GetModulePermissions()
        {
            var permissions = new List<PermissionInput>(5)
            {
               new PermissionInput(){ PermissionID = new Guid("{418D9725-3C83-4119-A76C-221E2371944C}"), PermissionName="用户管理", ModuleName= this.ModuleName}
              ,new PermissionInput(){ PermissionID = new Guid("{C834D9A6-AF92-4c4a-AB01-2277DB8A47A4}"), ParentID = new Guid("{418D9725-3C83-4119-A76C-221E2371944C}"),PermissionName="用户信息管理", ModuleName= this.ModuleName}
              ,new PermissionInput(){ PermissionID = new Guid("{A627F9C0-41F5-43e0-9D2F-6C5D1988CDC8}"), ParentID = new Guid("{418D9725-3C83-4119-A76C-221E2371944C}"),PermissionName="用户组管理", ModuleName= this.ModuleName}
              ,new PermissionInput(){ PermissionID = new Guid("{67A9B69F-A513-4c20-928E-532FB5EC4B42}"), ParentID = new Guid("{418D9725-3C83-4119-A76C-221E2371944C}"),PermissionName="角色管理", ModuleName= this.ModuleName}
              ,new PermissionInput(){ PermissionID = new Guid("{B16814AA-064D-42f5-B4B7-0E92A925C91F}"), ParentID = new Guid("{418D9725-3C83-4119-A76C-221E2371944C}"),PermissionName="权限管理", ModuleName= this.ModuleName}
            };
            return permissions;
        }

        #endregion

    }
}
